package cmd

import (
	"context"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

// Version implements the Version cmd.
type Init struct {
}

func (i *Init) Name() string      { return "init" }
func (i *Init) Usage() string     { return "" }
func (i *Init) ShortHelp() string { return "初始化项目" }
func (i *Init) DetailedHelp(f *flag.FlagSet) {
	fmt.Fprint(f.Output(), ``)
	f.PrintDefaults()
}

// Run prints Version information to stdout.
func (i *Init) Run(ctx context.Context, args ...string) error {
	wd, err := os.Getwd()
	if err != nil {
		return err
	}

	dir, err := ioutil.ReadDir(wd)
	if err != nil {
		return err
	}

	// If current directory is not empty, Ask the
	// user whether to continue creating
	if len(dir) != 0 {
		fmt.Print("当前目录不为空, 是否继续创建[Y/N]:")
		var input string
		_, err = fmt.Scanln(&input)
		if err != nil {
			return err
		}
		if strings.ToLower(strings.TrimSpace(input)) == "n" {
			return nil
		}
	}

	err = os.Mkdir("源码", os.ModePerm)
	if err != nil {
		return err
	}
	err = os.Mkdir("输出", os.ModePerm)
	if err != nil {
		return err
	}

	// Write the default startup class
	var content = `
公有 类 启动 {

	公有 静态 方法 main(参数列表: 文本[]) { 
		系统.输出.打印行("Hello")
	} 
} 
`
	err = ioutil.WriteFile("./源码/启动.mi", []byte(content), os.ModePerm)
	if err != nil {
		return err
	}

	// Write the project file
	var settings = `
{
    "version":"1.0",
    "dependents":[],
    "main_class":"启动"
}
`
	err = ioutil.WriteFile("项目.mip", []byte(settings), os.ModePerm)
	if err != nil {
		return err
	}
	fmt.Println("创建项目成功!")

	return nil
}

